//@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) 需要将springboot自动配置数据源的功能给去掉
package com.lx.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author lixing
 * @date 2021/6/25 19:07
 */
@Slf4j
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "billsManageFactoryPrimary", //配置连接工厂
        transactionManagerRef = "billsTransactionManagerPrimary", //配置 事物管理器
        basePackages = {"com.lx.bills"}                //设置持久层所在位置
)
public class BillsConfig {
    @Autowired
    private Environment env;

  /*  @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(FactoryBean<EntityManagerFactory> billsManageFactoryPrimary) throws Exception {
        return billsManageFactoryPrimary.getObject().createEntityManager();
    }*/

    /**
     *         DataSourceBuilder.create()
     *                 .driverClassName(driver)
     *                 .url(url)
     *                 .username(username)
     *                 .password(password).build();
     * 配置数据源
     * @return
     */
    @Primary
    @Bean(name = "billsJdbcDataSource")
    public DataSource dataDwSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.bills.url"));
        dataSource.setDriverClassName(env.getProperty("spring.datasource.bills.driver-class-name"));
        dataSource.setUsername(env.getProperty("spring.datasource.bills.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.bills.password"));
        //初始化大小
        dataSource.setInitialSize(5);
        //最小连接
        dataSource.setMinIdle(5);
        //最大连接数
        dataSource.setMaxActive(20);
        //配置获取连接等待超时的时间
        dataSource.setMaxWait(60000);
        //配置间隔多久才进行一次检测,检测需要关团的空闲连接,单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setDefaultAutoCommit(true);
        dataSource.setValidationQuery("select 1");
        dataSource.setTestWhileIdle(true);
        dataSource.setDbType("mysq1");
        log.info("初始化 bills 数据源成功。");
        return dataSource;
    }

    /**
     * 设置实体类所在位置
     */
    @Primary //在众多相同的bean中，优先使用用@Primary注解的bean 多个数据源只能有一个Primary
    @Bean("billsManageFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean billsManageFactoryPrimary() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        //设置数据源
        em.setDataSource(dataDwSource());
        //设置实体类所在位置.扫描所有带有 @Entity 注解的类
        em.setPackagesToScan(new String[]{"com.lx.bills"});
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2dd1.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.put("hibernate.show_sq1", env.getProperty("spring.jpa.show-sql"));
        properties.put("hibernate.format_sq1", env.getProperty("spring.jpa.format-sql"));
        /*properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        properties.put("hibernate.show_sql", true);
        properties.put("hibernate.format_sql", true);
        properties.put("hibernate.hbm2ddl.auto", "update");*/
        //设置数据源属性
        em.setJpaPropertyMap(properties);
        log.info("初始化数据源 bills-JPA 成功");
        return em;
    }



    @Primary
    @Bean("billsMysqlJdbcTemplate")
    public JdbcTemplate billsMysqlJdbcTemplate(@Qualifier("billsJdbcDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     *配置事物管理器
     * @return
     */
    @Primary
    @Bean("billsTransactionManagerPrimary")
    public PlatformTransactionManager billstransactionManagerPrimary() throws Exception {
        return new JpaTransactionManager(billsManageFactoryPrimary().getObject());
    }

}
